# -*- coding: utf-8 -*-
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "安盈太平长期返还型意外险"
    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                #年龄段
                "year":[str(i) for i in range(0,10)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["100000","200000"],
                #保障期限
                "days":["30y"],
                #交费方式
                "payType":["年交","月交"],
                #交费间隔
                "interval":["10","15"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(10, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "300000","500000"],
                # 保障期限
                "days": ["30y"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 交费间隔
                "interval": ["10", "15"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(18, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000","300000", "400000","500000","1000000"],
                # 保障期限
                "days": ["30y"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 交费间隔
                "interval": ["10", "15"]
            }
        }
        for k in plan:
            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["days"],plan[k]["payType"],plan[k]["interval"]):
                data = Helper.formatProductInfo( plan[k], v )
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( **data ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format( **data ) )
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        pageName: productAdd
        goods_id: 60497
        merchant_id: B2C
        toubaoli_money: 
        productCode: 50000738
        productId: ecf027c6-ac8e-4486-9181-b2328720c95a
        riskCode: 1200000097
        productName: 安盈太平长期返还型意外险
        insuredPrice: 177.4
        insured.birthday: 
        templateType: 1
        employee_id: 
        channel: GWSC-MENU-M5
        empNo: 
        newsCode: 
        twoMonthInsuredPrice: 354.80
        loginUserId: 
        insured.age: 02
        insured.sex: 2
        policy.amount: 10
        policy.dateRemark: 30
        policy.chargeType: 1
        policy.chargeYear: 10
        policy.showMessage: true
        person.mobilenum: 承保短信将发送至您的手机
        '''
        data = Helper.perfectJson( params )
        if dt["payType"] == "年交":
            data["insured.age"] = "0" + dt["year"] if int(dt["year"]) < 10 else dt["year"]
            data["insured.sex"] = "1" if dt["gender"] == "M" else "2"
            data["policy.amount"] = str( int(int( dt["money"])/10000))
            data["policy.chargeYear"] = dt["interval"]
            data["policy.chargeType"] = "1"
        else:
            data["insured.age"] = "0" + dt["year"] if int(dt["year"]) < 10 else dt["year"]
            data["insured.sex"] = "1" if dt["gender"] == "M" else "2"
            data["policy.amount"] = str(int(int(dt["money"]) / 10000))
            data["policy.chargeYear"] = dt["interval"]
            data["policy.chargeType"] = "4"
        productCode = self.filterProductCode( dt )
        data["productCode"] = productCode
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "计算保费成功" in r.text:
            price = Helper.decimalParse( r.json()["totalPremium"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.upTask( data )
            print("\n/*产品价格信息更新失败:%d*/"%dt["id"])
    #过滤产品Code
    def filterProductCode(self,params):
        if params["money"] != "1000000":
            if params["interval"] == "10":
                productCode = "50000738"
            else:
                productCode = "50000740"
            return productCode
        else:
            if params["interval"] == "10":
                productCode = "50000762"
            else:
                productCode = "50000764"
            return productCode
